package com.john.bms.config;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * 说明：错误异常拦截处理
 */
@Component
public class ExceptionConfiguration implements HandlerExceptionResolver{

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {
        ex.printStackTrace();
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
        Map<String, Object> attributes = new HashMap<>(8);
        ex.printStackTrace();
        if (ex instanceof UnauthenticatedException) {
            attributes.put("code", 50008);
            attributes.put("error", true);
            attributes.put("message", "token错误");
        } else if (ex instanceof UnauthorizedException) {
            attributes.put("code", 50012);
            attributes.put("error", true);
            attributes.put("message", "用户无权限");
        } else {
            attributes.put("code", 50014);
            attributes.put("error", true);
            attributes.put("message", ex.getMessage());
        }
        //mv.addObject("result",attributes);
        mv.addAllObjects(attributes);

        return mv;
    }
}
